import json

from sqlalchemy.orm import Session

from app.monitor_logs.models import MonitorLogExcludeKeyword
from app.monitor_logs.models import MonitorLogPolicy
from app.monitor_logs.models import MonitorLogService
from app.monitor_logs.models import MonitorLogCharacter
from core.logger import logger


def create_service_handler(db: Session, service_name: str, type: str):
    data = {"service_name": service_name, "type": type}
    try:
        log_service = MonitorLogService.add(db, data)
        if not log_service:
            # logger.error(f"create_service_handler create data fail => {json.dumps(data)}")
            logger.error(f"create_service_handler create data fail => ")
            return False
    except Exception as e:
        # logger.error(f"create_service_handler create data exception => {json.dumps(data)} {e}")
        logger.error(f"create_service_handler create data exception =>  {e}")
        return False
    return True


def create_policy_handler(db: Session, service_name: str, alarm_threshold: int = 50, is_maintain: int = 0,
                          maintain_begin_time: str = None, maintain_end_time: str = None, alarm_plan=None, notice_group=None):
    if notice_group is None:
        notice_group = []
    if alarm_plan is None:
        alarm_plan = {"date_range": [1, 2, 3, 4, 5, 6, 7], "time_range": {"start": "00:00:00", "end": "23:59:59"}}

    data = {"policy_name": service_name, "alarm_threshold": alarm_threshold, "is_maintain": is_maintain,
            "maintain_begin_time": maintain_begin_time, "maintain_end_time": maintain_end_time,
            "alarm_plan": alarm_plan, "notice_group": notice_group}
    try:
        log_service = db.query(MonitorLogService).filter(MonitorLogService.service_name == service_name).first()
        if not log_service:
            # logger.error(f"create_policy_handler query service_name fail => {service_name}")
            logger.error(f"create_policy_handler query service_name fail => ")
            return False
        data.update({"monitor_log_service_uuid": log_service.uuid})
        log_policy = MonitorLogPolicy.add(db, data)
        if not log_policy:
            # logger.error(f"create_policy_handler create data fail => {json.dumps(data)}")
            logger.error(f"create_policy_handler create data fail => ")
            return False
    except Exception as e:
        # logger.error(f"create_policy_handler create data exception => {json.dumps(data)} {e}")
        logger.error(f"create_policy_handler create data exception =>  {e}")
        return False
    return True


def create_exclude_keyword_handler(db: Session, service_name: str, username: str, exclude_keyword: str, is_active: int,
                                   effective_datetime: str = None, expiration_datetime: str = None, comment: str = None):
    data = {"service_name": service_name, "username": username, "exclude_keyword": exclude_keyword, "is_active": is_active,
            "effective_datetime": effective_datetime, "expiration_datetime": expiration_datetime, "comment": comment}
    try:
        log_service = db.query(MonitorLogService).filter(MonitorLogService.service_name == service_name).first()
        if not log_service:
            logger.error(f"create_exclude_keyword_handler query service_name fail => {service_name}")
            return False
        data.update({"monitor_log_service_uuid": log_service.uuid})
        exclude_keyword = MonitorLogExcludeKeyword.add(db, data)
        if not exclude_keyword:
            # logger.error(f"create_policy_handler create data fail => {json.dumps(data)}")
            logger.error(f"create_exclude_keyword_handler create data fail => ")
            return False
    except Exception as e:
        # logger.error(f"create_exclude_keyword_handler create data exception => {json.dumps(data)} {e}")
        logger.error(f"create_exclude_keyword_handler create data exception =>  {e}")
        return False
    return True


def create_log_character_handler(db: Session, service_name: str, content: str, count: int):
    data = {"service_name": service_name, "content": content, "count": count}
    try:
        log_service = db.query(MonitorLogService).filter(MonitorLogService.service_name == service_name).first()
        if not log_service:
            logger.error(f"create_exclude_keyword_handler query service_name fail => {service_name}")
            return False
        data.update({"monitor_log_service_uuid": log_service.uuid})
        log_character = MonitorLogCharacter.add(db, data)
        if not log_character:
            logger.error(f"create_log_character_handler create data fail => {service_name}")
            return False
    except Exception as e:
        logger.error(f"create_log_character_handler create data exception => {json.dumps(data)} {e}")
        return False
    return True


def update_service_handler(db: Session, service_uuid: int, type: str):
    try:
        log_service = db.query(MonitorLogService).filter(MonitorLogService.uuid == service_uuid).first()
        if not log_service:
            logger.error(f"update_service_handler query data fail => ")
            return False
        log_service.type = type
        db.commit()
    except Exception as e:
        # logger.error(f"create_service_handler create data exception => {json.dumps(data)} {e}")
        logger.error(f"update_service_handler update data exception =>  {e}")
        return False
    return log_service


def update_policy_handler(db: Session, service_uuid: int, alarm_threshold: int = 50, is_maintain: int = 0,
                          maintain_begin_time: str = None, maintain_end_time: str = None, alarm_plan=None, notice_group=None):
    try:
        log_policy = db.query(MonitorLogPolicy).filter(MonitorLogPolicy.monitor_log_service_uuid == service_uuid).first()
        if not log_policy:
            logger.error(f"update_policy_handler query monitor_log_service_uuid fail => ")
            return False
        log_policy.alarm_threshold = alarm_threshold
        log_policy.is_maintain = is_maintain
        log_policy.maintain_begin_time = maintain_begin_time
        log_policy.maintain_end_time = maintain_end_time
        log_policy.alarm_plan = alarm_plan
        log_policy.notice_group = notice_group
        db.commit()
    except Exception as e:
        logger.error(f"update_policy_handler update data exception =>  {e}")
        return False
    return log_policy


def update_exclude_keyword_handler(db: Session, service_uuid: str, username: str, exclude_keyword: str, is_active: int,
                                   effective_datetime: str = None, expiration_datetime: str = None):
    try:
        log_exclude_keyword = db.query(MonitorLogExcludeKeyword).filter(
            MonitorLogExcludeKeyword.monitor_log_service_uuid == service_uuid).first()
        if not log_exclude_keyword:
            logger.error(f"update_exclude_keyword_handler query policy_uuid fail => {service_uuid}")
            return False
        log_exclude_keyword.username = username
        log_exclude_keyword.exclude_keyword = exclude_keyword
        log_exclude_keyword.is_active = is_active
        log_exclude_keyword.effective_datetime = effective_datetime
        log_exclude_keyword.expiration_datetime = expiration_datetime
        db.commit()
        if not exclude_keyword:
            logger.error(f"update_policy_handler update data fail => ")
            return False
    except Exception as e:
        logger.error(f"update_exclude_keyword_handler update data exception =>  {e}")
        return False
    return log_exclude_keyword


def delete_service_handler(db: Session, service_uuid: int):
    try:
        log_policy = db.query(MonitorLogPolicy).filter(MonitorLogPolicy.monitor_log_service_uuid == service_uuid).first()
        log_character = db.query(MonitorLogCharacter).filter(
            MonitorLogCharacter.monitor_log_service_uuid == service_uuid).all()
        if log_policy or log_character:
            msg = "删除失败,删除日志服务前需完成相关日志策略与日志特征信息删除"
            logger.error(msg)
            return "relationships", msg
        log_service = db.query(MonitorLogService).filter(MonitorLogService.uuid == service_uuid).first()
        if not log_service:
            logger.error(f"delete_service_handler query service_uuid fail => {service_uuid}")
            return False, None
        log_service.delete(db)
        db.commit()
    except Exception as e:
        logger.error(f"delete_service_handler delete data exception =>  {e}")
        return False, None
    return True, None


def delete_policy_handler(db: Session, service_uuid: int):
    try:
        log_policy = db.query(MonitorLogPolicy).filter(MonitorLogPolicy.monitor_log_service_uuid == service_uuid).first()
        # log_exclude_keyword = db.query(MonitorLogExcludeKeyword).filter(
        #     MonitorLogExcludeKeyword.monitor_log_policy_uuid == log_policy.uuid).all()
        # if log_exclude_keyword:
        #     msg = "删除失败,删除服务策略前需完成相关日志日志关键字过滤信息删除"
        #     logger.error(msg)
        #     return "relationships", msg
        log_policy.delete(db)
        db.commit()
    except Exception as e:
        logger.error(f"delete_policy_handler delete data exception =>  {e}")
        return False, None
    return True, None


def delete_exclude_keyword_handler(db: Session, exclude_keyword_uuid: int):
    try:
        log_exclude_keyword = db.query(MonitorLogExcludeKeyword).filter(MonitorLogExcludeKeyword.uuid == exclude_keyword_uuid).first()
        if not log_exclude_keyword:
            logger.error(f"delete_exclude_keyword_handler query exclude_keyword_uuid fail => {exclude_keyword_uuid}")
            return False
        log_exclude_keyword.delete(db)
        db.commit()
    except Exception as e:
        logger.error(f"delete_exclude_keyword_handler delete data exception =>  {e}")
        return False
    return True


if __name__ == "__main__":
    from common.database import SessionLocal

    session = SessionLocal()
# "Failed to load driver class"
#     create_service_handler(session, "welab-skyscanner-matsu", "application")
#     print(create_policy_handler(session, "welab-skyscanner-matsu"))
#     create_exclude_keyword_handler(session, "welab-skyscanner-matsu", "boll.lai", "Failed to load driver class", True, "2023-03-28 09:00",
#                                    "2023-03-30 10:00")
    # create_log_character_handler(session, "qingluan-impala-daemon", "错误日志特征", 100)

    # session = SessionLocal()
    # log_service_obj = MonitorLogExcludeKeyword.add(session, {'username': "boll.lai",
    #                                                          'exclude_keyword': [], 'is_active': True,
    #                                                          "effective_datetime": "2023-03-27 09:00",
    #                                                          "expiration_datetime": "2023-03-27 09:30"})

    # monitor_log_policy = MonitorLogPolicy.add(session, {"policy_name": "user-center2", "alarm_threshold": 50, "is_maintain": True,
    #                                                     "maintain_begin_time": None,
    #                                                     "maintain_end_time": None, "alarm_plan": {"a": "1"}})
